
package com.dataset.manager.service.impl;

import com.dataset.manager.config.StorageConfig;
import com.dataset.manager.service.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

@Service
public class LocalStorageServiceImpl implements StorageService {

    @Autowired
    private StorageConfig storageConfig;

    @Override
    public void init() {
        // 确保基础存储目录存在
        try {
            Path basePath = Paths.get(storageConfig.getLocalPath());
            if (!Files.exists(basePath)) {
                Files.createDirectories(basePath);
            }
        } catch (IOException e) {
            throw new RuntimeException("初始化存储目录失败", e);
        }
    }

    @Override
    public String copyDataToTaskDirectory(String sourcePath, String id) throws IOException {
        Path source = Paths.get(sourcePath);
        Path baseStoragePath = Paths.get(storageConfig.getLocalPath());

        // 创建任务名称的子目录
        Path taskDirectory = baseStoragePath.resolve(id);
        if (!Files.exists(taskDirectory)) {
            Files.createDirectories(taskDirectory);
        }

        if (Files.isDirectory(source)) {
            // 复制整个目录
            Files.walkFileTree(source, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    Path targetFile = taskDirectory.resolve(source.relativize(file));
                    Files.createDirectories(targetFile.getParent());
                    Files.copy(file, targetFile, StandardCopyOption.REPLACE_EXISTING);
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                    Path targetDir = taskDirectory.resolve(source.relativize(dir));
                    Files.createDirectories(targetDir);
                    return FileVisitResult.CONTINUE;
                }
            });
        } else if (Files.exists(source)) {
            // 复制单个文件
            Path targetFile = taskDirectory.resolve(source.getFileName());
            Files.copy(source, targetFile, StandardCopyOption.REPLACE_EXISTING);
        }

        return taskDirectory.toString();
    }

    @Override
    public StorageService getStorageService(String storageType) {
        if ("local".equalsIgnoreCase(storageType)) {
            return this;
        }
        // S3存储在后续实现
        throw new UnsupportedOperationException("不支持的存储类型: " + storageType);
    }
}